﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GrailTechnology.OpenCalais;
using umbraco.presentation.nodeFactory;

namespace GrailTechnology.AutoTags.DataType
{
    public partial class AutoTagsIntegration : UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
    {
        public OpenCalaisService OpenCalaisController
        {
            get
            {
                if (ViewState["GTAutoTagsConnection"] == null)
                {
                    ViewState["GTAutoTagsConnection"] = new OpenCalaisService();
                }

                return ViewState["GTAutoTagsConnection"] as OpenCalaisService;
            }

            set { ViewState["GTAutoTagsConnection"] = value; }
        }

        public List<string> ChosenTags
        {
            get
            {
                if (ViewState["ChosenTags"] != null)
                {
                    return ViewState["ChosenTags"] as List<string>;
                }

                return new List<string>();
            }
            set
            {
                ViewState["ChosenTags"] = value;
            }
        }

        public List<string> AvailableTags
        {
            get
            {
                if (ViewState["AvailableTags"] != null)
                {
                    return ViewState["AvailableTags"] as List<string>;
                }

                return new List<string>();
            }
            set
            {
                ViewState["AvailableTags"] = value;
            }
        }

        private List<string> _tags = new List<string>();
        private string _umbracoValue;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SetStyles();
                LoadUmbracoValue();
                OpenCalaisController = new OpenCalaisService();
                if (OpenCalaisController.ContainsErrors)
                {
                    DisplayErrors(null);                  
                }

                BindTags();
            }
            else
            {
                SaveUmbracoValue();
            }
        }

        #region IUsercontrolDataEditor Members

        public object value
        {
            get
            {
                return _umbracoValue;
            }
            set
            {
                _umbracoValue = value.ToString();
            }
        }

        #endregion

        protected void buttonGetTags_Click(object sender, ImageClickEventArgs e)
        {
            literalErrors.Text = string.Empty;
            panelErrors.Visible = false;
            updateTags.Update();

            OpenCalaisController.GenerateTags(GetNodeProperties());

            if (OpenCalaisController.ContainsErrors)
            {
                DisplayErrors(null);
            }
            else
            {
                AvailableTags = OpenCalaisController.Tags;
                BindTags();
            }
        }

        private void DisplayErrors(string additionalMessage)
        {
            var sb = new StringBuilder();
            sb.Append("<ul>");
            foreach (var error in OpenCalaisController.Errors)
            {
                sb.AppendFormat("<li>{0}</li>", error);
            }
            if (!string.IsNullOrEmpty(additionalMessage))
            {
                sb.AppendFormat("<li>{0}</li>", additionalMessage);
            }
            sb.Append("</ul>");
            literalErrors.Text = sb.ToString();
            panelErrors.Visible = true;
            updateTags.Update();
        }

        private static string GetNodeProperties()
        {
            var content = new StringBuilder();
            var currentNode = new Node(int.Parse(HttpContext.Current.Request["id"]));
            var propertyAliases = Utils.GetNodeProperties();
            foreach(Property property in currentNode.Properties)
            {
                if (propertyAliases[0] == "all" || Utils.IsRequiredProperty(propertyAliases, property.Alias))
                {
                    content.AppendFormat("{0} ", property.Value);
                }
            }

            return content.ToString();
        }

        protected void repeaterGeneratedTags_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var tag = e.CommandArgument as string;
            if (!string.IsNullOrEmpty(tag))
            {
                var chosenTagList = ChosenTags;
                chosenTagList.Add(tag);
                ChosenTags = chosenTagList;

                var available = AvailableTags;
                if (available.Contains(tag))
                {
                    available.Remove(tag);
                }
                AvailableTags = available;

                BindTags();
            }
        }

        protected void repeaterTagList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var tagToRemove = e.CommandArgument as string;
            if (!string.IsNullOrEmpty(tagToRemove))
            {
                var tagList = ChosenTags;
                if (tagList.Contains(tagToRemove))
                {
                    tagList.Remove(tagToRemove);
                }

                ChosenTags = tagList;
                BindTags();
            }
        }

        private void BindTags()
        {
            repeaterGeneratedTags.DataSource = AvailableTags;
            repeaterGeneratedTags.DataBind();

            repeaterTagList.DataSource = ChosenTags;
            repeaterTagList.DataBind();

            updateTags.Update();
        }

        private void LoadUmbracoValue()
        {
            if (string.IsNullOrEmpty(_umbracoValue))
                ChosenTags = new List<string>();
            else
            {
                if (_umbracoValue.Substring(_umbracoValue.Length - 1, 1) == ",")
                    _umbracoValue = _umbracoValue.Substring(0, _umbracoValue.Length - 1);

                _tags.AddRange(_umbracoValue.Split(','));
                ChosenTags = _tags;
            }
        }

        private void SaveUmbracoValue()
        {
            _umbracoValue = string.Join(",", ChosenTags.ToArray());
        }

        private void SetStyles()
        {
            textAddOwn.Style.Add("border","2px solid #DDDDDD");
            textAddOwn.Style.Add("font-size","16px");
            textAddOwn.Style.Add("height","20px");
            textAddOwn.Style.Add("padding", "2px");
            textAddOwn.Style.Add("margin-bottom", "5px");
            textAddOwn.Style.Add("width", "190px;");
        }

        protected void buttonAdd_Click(object sender, EventArgs e)
        {
            if (textAddOwn.Text.Trim().Length > 0)
            {
                var tags = ChosenTags;
                tags.Add(textAddOwn.Text.Trim());
                ChosenTags = tags;
                BindTags();
            }
            else
            {
                DisplayErrors("Please enter a tag");
            }
        }
    }
}